﻿namespace IPMS.DAL
{
    using System;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;

    public class DataAccessLayer
    {
        public void AddParamToSQLCmd(SqlCommand sqlCmd, string paramId, SqlDbType sqlType, int paramSize, ParameterDirection paramDirection, object paramvalue)
        {
            if (sqlCmd == null)
            {
                throw new ArgumentNullException("sqlCmd");
            }
            if (paramId == string.Empty)
            {
                throw new ArgumentOutOfRangeException("paramId");
            }
            SqlParameter newSqlParam = new SqlParameter();
            newSqlParam.ParameterName = paramId;
            newSqlParam.SqlDbType = sqlType;
            newSqlParam.Direction = paramDirection;
            if (paramSize > 0)
            {
                newSqlParam.Size = paramSize;
            }
            if (paramvalue != null)
            {
                newSqlParam.Value = paramvalue;
            }
            sqlCmd.Parameters.Add(newSqlParam);
        }

        public void ExecuteNonQueryCmd(SqlCommand sqlCmd)
        {
            string ConnectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
            if (ConnectionString == string.Empty)
            {
                throw new ArgumentOutOfRangeException("ConnectionString");
            }
            if (sqlCmd == null)
            {
                throw new ArgumentNullException("sqlCmd");
            }
            using (SqlConnection cn = new SqlConnection(ConnectionString))
            {
                sqlCmd.Connection = cn;
                cn.Open();
                sqlCmd.ExecuteNonQuery();
            }
        }

        public void ExecuteScalarCmd(SqlCommand sqlCmd)
        {
            string ConnectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
            if (ConnectionString == string.Empty)
            {
                throw new ArgumentOutOfRangeException("ConnectionString");
            }
            if (sqlCmd == null)
            {
                throw new ArgumentNullException("sqlCmd");
            }
            using (SqlConnection cn = new SqlConnection(ConnectionString))
            {
                sqlCmd.Connection = cn;
                cn.Open();
                try
                {
                    sqlCmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        public void SetCommandType(SqlCommand sqlCmd, CommandType cmdType, string cmdText)
        {
            sqlCmd.CommandType = cmdType;
            sqlCmd.CommandText = cmdText;
        }
    }
}

